package cn.aitrox.ry.util;

import org.apache.commons.codec.binary.Hex;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class MacUtil {

    public static final String HMAC_SHA_256 = "HmacSHA256";

    public static String sign(String secretKey, String body, String algorithm) throws NoSuchAlgorithmException, InvalidKeyException {
        Mac sha256_HMAC = Mac.getInstance(algorithm);
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), algorithm);
        sha256_HMAC.init(secretKeySpec);
        byte[] hash = sha256_HMAC.doFinal(body.getBytes());
        String sign = Hex.encodeHexString(hash);
        return sign;
    }

}
